react state初始化问题

react state初始化问题

报错

1
Can't call setState on a component that is not yet mounted. This is a no-op, but it might indicate a bug in your application. Instead, assign to `this.state` directly or define a `state = {};` class property with the desired state in the *** component.

大致:

不能再一个组件尚未mounted时调用 setState() 方法,这是一个空操作,但是可能会导致bug,所以, 直接给this.state 赋值,或者定义成state = {};

问题代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import React from 'react';
import { Icon } from 'antd';

class ProjMain extends React.Component {
constructor(props) {
super(props);
this.setState({
docDetail: {}
})
}

render() {
return (
<div id={Style.projIndex}>
<h1 style={{fontSize: 40}}>{this.state.docDetail))}</h1>
</div>
);
}
}

export default ProjMain;

render() 方法中如果使用了 this.state.docDetail,会导致编译报错

error

仔细检查代码

1
2
3
4
5
6
constructor(props) {
super(props);
this.setState({
docDetail: {}
})
}

constructor 里使用了 setState,改为直接赋值后正常

-------------本文结束感谢您的阅读-------------